package com.zhq.tool.view;

import com.alibaba.fastjson.JSON;
import com.zhq.tool.db.LocalStorage;
import com.zhq.tool.util.*;
import com.zhq.tool.widget.CopyTextField;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;
import java.util.Date;
import java.util.Vector;
import java.util.function.Predicate;

/**
 * @ProjectName: YcTool
 * @Package: com.yc.tool.util
 * @ClassName: MainActivity
 * @Author: jacky
 * @Description: 启动界面
 * @Date: 2022/1/28 10:38
 * @Version: 1.0
 */
public class MainActivity extends JFrame implements ActionListener {

    private JTextField moneyText, interestRateText;
    private JComboBox<String> yearComboBox;
    private JComboBox<Integer> yearFirstComboBox, mouthComboBox, tqhkYearComboBox, tqhkMouthComboBox;
    private Vector<Integer> mouthYear = new Vector<>();
    private Vector<Integer> scYearList = new Vector<>();
    private Vector<Integer> scMouthList = new Vector<>();
    private Vector<Integer> tqYearList = new Vector<>();
    private Vector<Integer> tqMouthList = new Vector<>();
    private JRadioButton tkTypeRb1, tkTypeRb2;
    private JTextField hkMoneyText;
    private JButton calculateButton;
    private JList<String> list;
    private Vector<String> mortgageMouth;
    private LocalStorage localStorage = null;

    private MainActivity() {
        setTitle("v1.0房贷利率工具");
        setResizable(false);
        // 设置界面可见
        setVisible(true);
        Image imageIcon = Toolkit.getDefaultToolkit().getImage("./resource/logo.ico");
        setIconImage(imageIcon);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(380, 600);
        setLocationRelativeTo(null);//传入参数null 即可让JFrame 位于屏幕中央, 这个函数若传入一个Component ,则JFrame位于该组件的中央
        JPanel panel = new JPanel();
        // 添加面板
        add(panel);

        /* 布局部分我们这边不多做介绍
         * 这边设置布局为 null
         */
        panel.setLayout(null);
        panel.setForeground(Color.gray);

        // 创建 JLabel
        JLabel userLabel = new JLabel("贷款类别:");
        /* 这个方法定义了组件的位置。
         * setBounds(x, y, width, height)
         * x 和 y 指定左上角的新位置，由 width 和 height 指定新的大小。
         */
        userLabel.setBounds(10, 20, 80, 25);
        panel.add(userLabel);


        ButtonGroup group = new ButtonGroup();
        tkTypeRb1 = new JRadioButton("公积金贷款");    //创建JRadioButton对象
        tkTypeRb1.setBounds(100, 20, 100, 25);
        tkTypeRb2 = new JRadioButton("商业贷款", true);    //创建JRadioButton对象
        tkTypeRb2.setBounds(200, 20, 100, 25);
        //添加item事件
        tkTypeRb1.addItemListener(e -> interestRateText.setText("3.25"));
        tkTypeRb2.addItemListener(e -> interestRateText.setText(""));

        group.add(tkTypeRb1);
        group.add(tkTypeRb2);
        panel.add(tkTypeRb1);
        panel.add(tkTypeRb2);
        // 贷款总额
        JLabel codeTextLabel = new JLabel("贷款总额:");
        codeTextLabel.setBounds(10, 50, 80, 25);
        panel.add(codeTextLabel);
        /*
         *这个类似用于输入的文本域
         */
        moneyText = new JTextField(20);
        moneyText.setBounds(100, 50, 100, 25);
        moneyText.setDocument(new MyRegExp("[0-9]{1,}"));
        panel.add(moneyText);
        // 后缀
        JLabel moneyLabel = new JLabel("万元");
        int width = codeTextLabel.getWidth() + moneyText.getWidth() + 30;
        moneyLabel.setBounds(width, 50, 80, 25);
        panel.add(moneyLabel);

        // 输入转换结果文本域
        JLabel convertResult = new JLabel("按揭年数:");
        convertResult.setBounds(10, 80, 80, 25);
        panel.add(convertResult);

        mortgageMouth = new Vector<>();
        for (int i = 30; i >= 1; i--) {
            mortgageMouth.add(i + "年" + "（" + (12 * i) + "期）");
            mouthYear.add((12 * i));
        }
        yearComboBox = new JComboBox<>(mortgageMouth);
        yearComboBox.setSelectedIndex(0);
        yearComboBox.setBounds(100, 80, 165, 25);
        panel.add(yearComboBox);
        //利率标签
        JLabel linkLabel = new JLabel("利率：");
        linkLabel.setBounds(10, 110, 80, 25);
        panel.add(linkLabel);
        //利率
        interestRateText = new JTextField(20);
        interestRateText.setBounds(100, 110, 100, 25);
        // interestRateText.setDocument(new MyRegExp("[0-9]{1,.}"));
        panel.add(interestRateText);
        JLabel percentageLabel = new JLabel("%");
        int percentageWidth = linkLabel.getWidth() + interestRateText.getWidth() + 30;
        percentageLabel.setBounds(percentageWidth, 110, 80, 25);
        panel.add(percentageLabel);

        drawSchkUi(panel);
        drawHkfsUi(panel);

        //开始计算
        calculateButton = new JButton("开始计算");
        calculateButton.setBounds(100, 320, 200, 25);
        calculateButton.addActionListener(this);
        panel.add(calculateButton);

        JLabel ycLabel = new JLabel("计算结果");
        ycLabel.setForeground(Color.BLACK);//设置文字的颜色
        ycLabel.setBounds(10, 345, 150, 25);
        panel.add(ycLabel);


        list = new JList<>();


        // 允许可间断的多选
        list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        list.setLayoutOrientation(JList.VERTICAL);
        JScrollPane ps = new JScrollPane();
        ps.setBounds(10, 375, 360, 180);
        ps.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);//垂直滚动
        ps.setViewportView(list);
        panel.add(ps);
        init();

    }


    /**
     * 首次还款及提前还款
     *
     * @param groupView
     */
    private void drawSchkUi(JPanel groupView) {
        // 首次还款
        JLabel scLabel = new JLabel("首次还款:");
        scLabel.setBounds(10, 140, 80, 25);
        groupView.add(scLabel);


        int currentDate = Integer.parseInt(DateUtil.getNowDate("yyyy", new Date()));
        for (int i = currentDate; i >= (currentDate - 20); i--) {
            scYearList.add(i);
        }
        yearFirstComboBox = new JComboBox<>(scYearList);
        yearFirstComboBox.setSelectedIndex(0);
        yearFirstComboBox.setBounds(100, 140, 80, 25);
        groupView.add(yearFirstComboBox);

        int yearLabelWidth = scLabel.getWidth() + yearFirstComboBox.getWidth() + 25;
        JLabel yearLabel = new JLabel("年");
        yearLabel.setBounds(yearLabelWidth, 140, 30, 25);
        groupView.add(yearLabel);

        for (int i = 1; i <= 12; i++) {
            scMouthList.add(i);
        }
        int mouthX = yearLabelWidth + 25;
        mouthComboBox = new JComboBox<>(scMouthList);
        mouthComboBox.setSelectedIndex(0);
        mouthComboBox.setBounds(mouthX, 140, 50, 25);
        groupView.add(mouthComboBox);

        int mouthLabelX = mouthX + 25;
        JLabel mouthLabel = new JLabel("月");
        mouthLabel.setBounds(mouthLabelX, 140, 30, 25);
        groupView.add(mouthLabel);


        // 提前还款
        JLabel tqhkLabel = new JLabel("提前还款:");
        tqhkLabel.setBounds(10, 170, 80, 25);
        groupView.add(tqhkLabel);
        /**
         * 年限
         * 当前日期推30年
         */
        for (int i = currentDate; i <= (currentDate + 30); i++) {
            tqYearList.add(i);
        }
        tqhkYearComboBox = new JComboBox<>(tqYearList);
        tqhkYearComboBox.setSelectedIndex(0);
        tqhkYearComboBox.setBounds(100, 170, 80, 25);
        groupView.add(tqhkYearComboBox);
        int tqhkYearLabelWidth = tqhkLabel.getWidth() + tqhkYearComboBox.getWidth() + 25;
        JLabel tqhkYearLabel = new JLabel("年");
        tqhkYearLabel.setBounds(tqhkYearLabelWidth, 170, 30, 25);
        groupView.add(tqhkYearLabel);
        /**
         * 月份
         */
        for (int i = 1; i <= 12; i++) {
            tqMouthList.add(i);
        }
        int tqhkMouthX = yearLabelWidth + 25;
        tqhkMouthComboBox = new JComboBox<>(tqMouthList);
        tqhkMouthComboBox.setSelectedIndex(0);
        tqhkMouthComboBox.setBounds(tqhkMouthX, 170, 50, 25);
        groupView.add(tqhkMouthComboBox);

        int tqhkMouthLabelX = tqhkMouthX + 25;
        JLabel tqhkMouthLabel = new JLabel("月");
        tqhkMouthLabel.setBounds(tqhkMouthLabelX, 170, 30, 25);
        groupView.add(tqhkMouthLabel);


    }

    private JRadioButton rb1, rb2, rb3, rb4;

    /**
     * 还款方式Ui
     */
    private void drawHkfsUi(JPanel groupView) {
        // 还款方式
        JLabel hkfsLabel = new JLabel("还款方式:");
        hkfsLabel.setBounds(10, 200, 80, 25);
        groupView.add(hkfsLabel);
        ButtonGroup group = new ButtonGroup();
        rb1 = new JRadioButton("部分提前还款", true);
        rb1.setBounds(100, 200, 115, 25);
        rb2 = new JRadioButton("一次性还款", false);
        rb2.setBounds(100, 230, 115, 25);
        group.add(rb1);
        group.add(rb2);
        groupView.add(rb1);

        int hkMoneyWidth = hkfsLabel.getWidth() + rb1.getWidth() + 25;
        hkMoneyText = new CopyTextField();
        hkMoneyText.setBounds(hkMoneyWidth, 200, 80, 25);
        groupView.add(hkMoneyText);
        // 后缀
        JLabel moneyLabel = new JLabel("万元");
        int width = hkMoneyWidth + hkMoneyText.getWidth() + 10;
        moneyLabel.setBounds(width, 200, 30, 25);
        groupView.add(moneyLabel);
        groupView.add(rb2);

        //计算方式
        JLabel jsfsLabel = new JLabel("计算方式:");
        jsfsLabel.setBounds(10, 260, 80, 25);
        groupView.add(jsfsLabel);
        /**
         * 计算方式
         */
        ButtonGroup jsGroup = new ButtonGroup();
        rb3 = new JRadioButton("缩短还款期限，月还款额基本不变", true);
        rb3.setBounds(100, 260, 250, 25);
        rb4 = new JRadioButton("减少月还款额，还款期限不变", false);
        rb4.setBounds(100, 290, 200, 25);
        jsGroup.add(rb3);
        jsGroup.add(rb4);
        groupView.add(rb3);
        groupView.add(rb4);


    }

    /**
     * 初始化操作
     */
    private void init() {
        //初始化配置
        localStorage = FileUtils.getLocalStorage();
        if (!StringUtils.isEmpty(localStorage.getTotalMoney())) {
            moneyText.setText(localStorage.getTotalMoney());
        }
        if (!StringUtils.isEmpty(localStorage.getMortgage())) {
            int position = mortgageMouth.indexOf(localStorage.getMortgage());
            yearComboBox.setSelectedIndex(position);
        }
        if (!StringUtils.isEmpty(localStorage.getYearRate())) {
            interestRateText.setText(localStorage.getYearRate());
        }
        if (localStorage.getScYear() != null && localStorage.getScMouth() != null) {
            yearFirstComboBox.setSelectedIndex(scYearList.indexOf(localStorage.getScYear()));
            mouthComboBox.setSelectedIndex(scMouthList.indexOf(localStorage.getScMouth()));
        }

        if (localStorage.getTqYear() != null && localStorage.getTqMouth() != null) {
            tqhkYearComboBox.setSelectedIndex(tqYearList.indexOf(localStorage.getTqYear()));
            tqhkMouthComboBox.setSelectedIndex(tqMouthList.indexOf(localStorage.getTqMouth()));
        }
        if (!StringUtils.isEmpty(localStorage.getTqhkMoney())) {
            hkMoneyText.setText(localStorage.getTqhkMoney());
        }
        if (localStorage.getHkMethod() != null) {
            if (localStorage.getHkMethod().equals(1)) {
                rb1.setSelected(true);
                rb2.setSelected(false);
            } else {
                rb2.setSelected(true);
                rb1.setSelected(false);
            }
        }
        //计算方式
        if (localStorage.getJsMethod() != null) {
            if (localStorage.getJsMethod().equals(1)) {
                rb3.setSelected(true);
                rb4.setSelected(false);
            } else {
                rb4.setSelected(true);
                rb3.setSelected(false);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String totalMoneyStr = moneyText.getText();//总额
        String yearRateStr = interestRateText.getText();//年率
        if (totalMoneyStr == null || "".equals(totalMoneyStr)) {
            JOptionPane.showMessageDialog(this, "贷款总额不能为空！", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (yearRateStr == null || "".equals(yearRateStr)) {
            JOptionPane.showMessageDialog(this, "年率不能为空！", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }
        double totalMoney = Double.parseDouble(totalMoneyStr) * 10000;
        double yearRate = Double.parseDouble(yearRateStr);
        int mouth = mouthYear.get(yearComboBox.getSelectedIndex());//月份
        int scYear = scYearList.get(yearFirstComboBox.getSelectedIndex());//首次还款年份
        int scMouth = scMouthList.get(mouthComboBox.getSelectedIndex());//首次还款月份
        int tqYear = tqYearList.get(tqhkYearComboBox.getSelectedIndex());//首次还款年份
        int tqMouth = tqMouthList.get(tqhkMouthComboBox.getSelectedIndex());//首次还款月份

        //存储到本地
        localStorage.setTotalMoney(totalMoneyStr);
        localStorage.setYearRate(yearRateStr);
        localStorage.setMortgage(mortgageMouth.get(yearComboBox.getSelectedIndex()));
        localStorage.setMortgageMouth(mouth);
        localStorage.setScYear(scYear);
        localStorage.setScMouth(scMouth);
        localStorage.setTqYear(tqYear);
        localStorage.setTqMouth(tqMouth);
        double tqHKMoney = 0.0d;
        //提前部分还款
        if (rb1.isSelected()) {
            String tqHKMoneyStr = hkMoneyText.getText();//提前还款钱
            if (tqHKMoneyStr == null || "".equals(tqHKMoneyStr)) {
                JOptionPane.showMessageDialog(this, "提前还款钱不能为空！", "提示", JOptionPane.ERROR_MESSAGE);
                return;
            }
            localStorage.setTqhkMoney(tqHKMoneyStr);
            tqHKMoney = Double.parseDouble(tqHKMoneyStr) * 10000;
            localStorage.setHkMethod(1);
        } else {
            //一次性还款
            tqHKMoney = totalMoney;
            localStorage.setHkMethod(2);
        }

        try {
            int payTimes = DateUtil.getTime(scYear + "-" + scMouth, tqYear + "-" + tqMouth);//已还完次数
            if(rb3.isSelected()){
                //缩短还款期限，月还款基本不变
                localStorage.setJsMethod(1);
                String[] result = CalculateUtils.calculateEqualPrincipalAndInterestApart(totalMoney, mouth, tqHKMoney, payTimes, yearRate);
                ListModel<String> jList1Model =  new DefaultComboBoxModel<>(result);
                list.setModel(jList1Model);
            }else{
                //减少月还额，还款期限不变
                localStorage.setJsMethod(2);
                String[] result = CalculateUtils.calculateEqualPrincipalAndInterestApart2(totalMoney, mouth, tqHKMoney, payTimes, yearRate);
                ListModel<String> jList1Model =  new DefaultComboBoxModel<> (result);
                list.setModel(jList1Model);
            }
            FileUtils.saveFile(localStorage.getPath(), JSON.toJSONString(localStorage));
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    MainActivity frame = new MainActivity();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


}
